package erp

import (
	"context"
	"fmt"
	"strings"

	"mall/common/resultx"
	"mall/service/order/model"
	"mall/service/order/rpc/internal/svc"
	"mall/service/order/rpc/internal/utils/erpstatus"
	"mall/service/order/rpc/types/order"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendErpSetOrderStatusLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendErpSetOrderStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendErpSetOrderStatusLogic {
	return &BackendErpSetOrderStatusLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// erp订单状态同步本地
func (l *BackendErpSetOrderStatusLogic) BackendErpSetOrderStatus(in *order.ErpSetOrderStateReq) (*order.BaseResp, error) {
	if (in.Ids == nil || len(*in.Ids) == 0) && (in.OrderSns == nil || len(*in.OrderSns) == 0) {
		logrus.Info(fmt.Sprintf("BackendErpSetOrderStatus err : Ids or,OrderSns empty"))
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}
	if in.TradeState == nil {
		logrus.Info(fmt.Sprintf("BackendErpSetOrderStatus err : TradeState is empty"))
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}
	var filterMap = make(map[string]map[string][]any)
	if in.Ids != nil && len(*in.Ids) > 0 {
		var oid []any
		if len(strings.Split(*in.Ids, ",")) > 0 {
			for _, ids := range *in.Ids {
				oid = append(oid, ids)
			}
		}
		if len(oid) > 0 {
			filterMap[model.OrderColumns.ID] = map[string][]any{
				"in": oid,
			}
		}
	}
	if in.OrderSns != nil && len(*in.OrderSns) > 0 {
		var sns []any
		orderSns := strings.Split(*in.OrderSns, ",")
		if len(orderSns) > 0 {
			for _, sn := range orderSns {
				sns = append(sns, sn)
			}
		}
		if len(sns) > 0 {
			filterMap[model.OrderColumns.OrderSN] = map[string][]any{
				"in": sns,
			}
		}
	}
	if len(filterMap) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}
	orderList, _, err := l.svcCtx.Order.GetList(l.ctx, model.M{}, -1, filterMap)
	if err != nil {
		return nil, err
	}
	var ids []uint64
	var idMap = map[uint64]struct{}{}
	if len(orderList) > 0 {
		for _, v := range orderList {
			if _, ok := idMap[v.ID]; !ok {
				ids = append(ids, v.ID)
				idMap[v.ID] = struct{}{}
			}
		}
	}
	status := erpstatus.ErpOrderStatusToOrderStatus(*in.TradeState)
	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, resultx.StatusError(resultx.DB_ERROR, "")
	}
	err = l.svcCtx.Order.UpdateBatch(l.ctx, tx, ids, model.M{
		model.OrderColumns.TradeState: int8(status),
	})
	if err != nil {
		tx.Rollback()
		return nil, err
	}
	tx.Commit()
	logrus.Info(fmt.Sprintf("BackendErpSetOrderStatus Ids: %+v,OrderStatus: %+v", ids, status))
	return &order.BaseResp{
		Msg: "修改成功",
	}, nil
}
